/*
 * Created on 2008-3-7
 *
 * TODO 
 */
package jacky.lanlan.song.extension.struts.interceptor;

import java.lang.reflect.Method;
import java.util.List;

import jacky.lanlan.song.extension.struts.InfrastructureKeys;
import jacky.lanlan.song.extension.struts.annotation.Upload;
import jacky.lanlan.song.extension.struts.resource.ResourcePersistence;
import jacky.lanlan.song.extension.struts.util.ConcurrentCache;
import jacky.lanlan.song.extension.struts.util.Factory;
import jacky.lanlan.song.extension.struts.util.ReturnableHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.upload.FormFile;

/**
 * 处理资源上载的拦截器。优先级200。
 * @author Jacky.Song
 */
public class UploadInterceptor extends ActionInterceptorAdapter {

	private static final Logger logger = Logger.getLogger(UploadInterceptor.class);
	
	// 上载处理器缓存 [Factory全类名 -> 上载处理器]
	private ConcurrentCache<String,ResourcePersistence,Class<? extends Factory<ResourcePersistence>>> persistenceCache=
		new ConcurrentCache<String,ResourcePersistence,Class<? extends Factory<ResourcePersistence>>>(
				new ReturnableHandler<Class<? extends Factory<ResourcePersistence>>,ResourcePersistence>(){
					public ResourcePersistence doWith(
							Class<? extends Factory<ResourcePersistence>> data) {
						try {
							return data.newInstance().create();
						}
						catch (Exception e) {
							logger.error("缓存上载处理器 ["+data+"] 时出错",e);
						}
						return null;
					}
		});
	
	@SuppressWarnings("unchecked")
	public String preHandle(HttpServletRequest request,
			HttpServletResponse response, Object action) throws Exception {
		Method method=(Method)request.getAttribute(InfrastructureKeys.EXECUTION);
		if(method.isAnnotationPresent(Upload.class)) { //如果有上载的资源
			List<FormFile> uploadFiles=(List) request.getAttribute(InfrastructureKeys.UPLOAD_DATA);
			//创建并缓存持久化器
			Class<? extends Factory<ResourcePersistence>> rpFactory=method.getAnnotation(Upload.class).factory();
			ResourcePersistence rp = persistenceCache.cacheIfAbsent(
					rpFactory.getName(), rpFactory);
			
			rp.persistence(uploadFiles);// 持久化上载资源(上载)
		}
		
		return null; //继续调用下面的拦截器
	}

	public int priority() {
		return 200;//优先级在默认拦截器中高于DownloadInterceptor
	}
	
}
